package com.leo.blog.util;



import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Classname CacheUtils
 * @Description TODO
 * @Date 2022/11/25 21:29
 * @Created by XiongXiong
 * @Author: X.I.O
 *
 * 缓存工具类
 */
public class CacheUtils {

    private static final Integer SIZE=1000000;

    private static ConcurrentHashMap<String,Object> CACHE;

    private static void init(){
        if (CACHE == null) {
            CACHE = new ConcurrentHashMap(SIZE);;
        }
    }

    public static Object getObject(String key){
        init();
        Object val=CACHE.get(key);
        if(val == null){
            return null;
        }
        CacheModel cacheModel=(CacheModel) val;
        if(cacheModel.getExpireTime()!=null){
            Date expireTime=cacheModel.getExpireTime();
            Date nowDate=new Date();
            if(expireTime.getTime() < nowDate.getTime()){
                CACHE.remove(key);
                return null;
            }
        }
        return CACHE.get(key);
    }

    public static void putObject(String key,Object value){
        init();
        CacheModel cacheModel=getCacheModel();
        cacheModel.setKey(key);
        cacheModel.setValue(value);
        cacheModel.setCreateDate(new Date());
        CACHE.put(key, cacheModel);
    }

    public static void putExpireTime(String key, Object value,int secords) {
        init();
        Date exporeDate=DateUtils.getExpireDate(secords);
        CacheModel cacheModel = getCacheModel();
        cacheModel.setKey(key);
        cacheModel.setValue(value);
        cacheModel.setExpireTime(exporeDate);
        cacheModel.setCreateDate(new Date());
        CACHE.put(key, cacheModel);
    }

    public static void removeCacheByKey(String key){
        init();
        Object val=CACHE.get(key);
        if(val!=null){
            CACHE.remove(key,val);
        }
    }


    private static CacheModel getCacheModel(){
        return new CacheModel();
    }


}
